<template>
  <div id="map-container-market">
    <div v-if="showLinkerNumber" class="nav-bar">当前共有{{totalLinkerNum}}个楼盘</div>
    <img @click="retryLocation" class="location-icon" :class="currentLinker.linkerId && 'location-suspension'" :src="require('IMG/mapSearch/location-icon.png')" />
    <div class="linker-shade">
      <estate-item @click="$router.push(`/market/${currentLinker.linkerId}`)" v-if="currentLinker.linkerId" :info="currentLinker"></estate-item>
    </div>
  </div>
</template>

<script>
import TMap from '@/utils/tMap'
import { mapGetters } from 'vuex'
import EstateItem from 'COMP/EstateItem'
import commonService from '@/services/commonService'
import * as types from '@/store/mutation-types'
export default {
  data() {
    return {
      map: null,
      latLng: {
        lat: 31.28706,
        lng: 114.606628,
      },
      markList: [],
      city: '全国',
      houseList: [],
      linkerList: [],  //对应全部楼盘列表
      currentLinker: {},
      zoom: 5,
      geocoder: '',
      totalLinkerNum: 0,
      level: 0,
      showLinkerNumber: false,  //是否显示楼盘总数
    }
  },
  computed: {
    ...mapGetters(['userArea', 'userInfo'])
  },
  components: {
    EstateItem
  },
  watch: {
    level(level) {
      let timer = null
      if (level == 3) {
        this.showLinkerNumber = true;
        timer = setTimeout(_ => {
          this.showLinkerNumber = false;
          clearTimeout(timer)
        }, 3000)
      }
    }
  },
  created() {
    const wxLocation = JSON.parse(window.localStorage.getItem('wxLocation')) || {
      latitude: '',
      longitude: '',
      city: ''
    };
    const userArea = this.userArea;

    if (userArea.latitude || wxLocation.latitude) {
      this.latLng = {
        lat: userArea.latitude || wxLocation.latitude,
        lng: userArea.longitude || wxLocation.longitude
      }

      this.city = userArea.city || wxLocation.city
    }
    this.initMap(this.latLng.lat, this.latLng.lng)
    this.getRegionTotal(1)
  },

  methods: {
    async initMap(lat, lng) {
      await TMap()
      this.map = new qq.maps.Map(document.getElementById('map-container-market'), {
        center: new qq.maps.LatLng(lat, lng), // 地图的中心地理坐标
        zoom: 5,
        minZoom: 3,
        maxZoom: 20,
        disableDefaultUI: true, // 禁止所有的默认控件
        scrollwheel: false,
        keyboardShortcuts: false,
        panControl: false,
      })
      qq.maps.event.addListener(this.map, 'zoom_changed', () => {
        this.zoomChange(this.map.getZoom())
      })
      this.geocoder = new qq.maps.Geocoder({
        complete: (result) => {
          if (this.zoom <= 5) {
            this.city = '全国'
            this.getRegionTotal(1)
          } else if (this.zoom > 5 && this.zoom <= 7) {
            if (result.detail.address.indexOf('自治区') > -1) {
              this.city = result.detail.address.split('区')[0].slice(2) + '区'
            } else {
              this.city = result.detail.address.split('省')[0].slice(2) + '省'
            }
            this.getRegionTotal(2)
          } else if (this.zoom > 7 && this.zoom <= 10) {
            if (result.detail.address.indexOf('县') > -1) {
              this.city = result.detail.address.split('县')[0].split('省')[1] + '县'
            } else if (result.detail.address.indexOf('自治区') > -1) {
              this.city = result.detail.address.split('自治区')[1].split('市')[0] + '市'
            } else {
              this.city = result.detail.address.split('市')[0].split('省')[1] + '市'
            }
            this.getRegionTotal(3)
          } else {
            this.city = ''
            this.getRegionLinkers()
          }
        }
      });

      if (this.latLng.lat == 31.28706 && this.latLng.lng == 114.606628) {
        this.map.setZoom(5)
      } else {
        this.map.setZoom(13)
      }

      // this.updateMark()
    },
    getCity() {
      this.latLng = this.map.getCenter()
      var latLng = new qq.maps.LatLng(this.latLng.lat, this.latLng.lng)
      this.geocoder.getAddress(latLng)
    },
    zoomChange(zoom) {
      this.zoom = zoom
      this.getCity()
    },
    getRegionLinkers() {
      commonService.getRegionLinkers({
        longitude: this.latLng.lng,
        latitude: this.latLng.lat
      }).then(res => {
        let arr = []
        res.forEach(el => {
          let obj = {
            linkerId: el.linkerId,
            latitude: el.latitude,
            level: 3,
            linkerNum: '',
            longitude: el.longitude,
            name: el.linkerName,
            priceUnit: el.priceUnit,
            linkerPrice: el.linkerPrice,
          }
          arr.push(obj)
        })
        this.houseList = arr
        this.linkerList = res;
        if (this.houseList.length) {
          this.updateMark();
        }
      }).catch()
    },
    getRegionTotal(level) {
      commonService.getRegionTotal({
        parentName: this.city,
        longitude: this.latLng.lng,
        latitude: this.latLng.lat,
        level: level
      }).then(res => {
        this.houseList = res
        if (this.houseList.length) {
          this.updateMark()
          // 如果level 等于3， 计算楼盘数量
          this.level = level;
          if (level == 3) {
            let totalLinkerNum = 0;
            res.forEach(item => {
              totalLinkerNum += item.linkerNum;
            })
            this.totalLinkerNum = totalLinkerNum;
          }
        }

      }).catch()
    },
    updateMark() {
      // clean 当前
      this.cleanMark()
      this.markMaker()
    },
    cleanMark() {
      while (this.markList.length > 0) {
        let shift = this.markList.shift()
        shift.setMap(null)
      }
    },
    markMaker() {
      let scaleSize = new qq.maps.Size(85, 85)
      let html = ''
      for (let temp of this.houseList) {
        const current = this.currentLinker.linkerId == temp.linkerId;
        if (temp.linkerNum) {
          html = `<div class="area-text">
            <p class="name">${temp.name}</p>
            <p style="margin-top: 4px">${temp.linkerNum}个</p>
          </div>`
        } else {
          scaleSize = new qq.maps.Size(148, 70)
          html = `
            <div class="linker-text" style="background: ${current ? 'rgba(255, 156, 56, 0.9)' : 'rgba(0, 122, 230, 0.9)'}">
            <p class="name">${temp.name}</p>
            <p style="margin-top: 4px">${temp.linkerPrice}${temp.priceUnit}</p>
            <span class="arrow" style="border-color: ${current ? 'rgba(255, 156, 56, 0.9) transparent transparent transparent' : 'rgba(0, 122, 230, 0.9) transparent transparent transparent'}" ></span>
          </div>`
        }
        let marker = new qq.maps.Marker({
          icon: new qq.maps.MarkerImage('', null, null, null, scaleSize),
          map: this.map,
          position: new qq.maps.LatLng(temp.latitude, temp.longitude),
          decoration: new qq.maps.MarkerDecoration(html, new qq.maps.Point(0, 0))
        })
        qq.maps.event.addListener(marker, 'click', (e) => {

          if (temp.linkerId) {
            this.getCurrentLinker(temp.linkerId);
            this.updateMark();
            // this.$router.push(`/market/${temp.linkerId}`)
          } else {
            let zoom = this.map.zoom
            this.map.setCenter(new qq.maps.LatLng(e.latLng.lat, e.latLng.lng))
            if (zoom > 5 && zoom <= 7) {
              this.city = temp.name
              this.map.setZoom(zoom + 1)
            } else {
              this.map.setZoom(zoom + 2)
            }
          }
        })
        this.markList.push(marker)
      }
    },
    // 重新定位
    retryLocation() {
      wx.getLocation({
        type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
        success: res => {
          this.getCityLocation(res)
        },
        fail: () => {
          this.$toast('定位失败')
        },
        cancel: res => {
          this.$toast('定位取消')
        }
      })
    },
    // 获取定位
    async getCityLocation(data) {
      const result = await commonService.getLocation(data.longitude, data.latitude)
      this.$store.commit(types['USER_AREA'], {
        city: result,
        longitude: data.longitude,
        latitude: data.latitude
      })
      window.localStorage.setItem('wxLocation', JSON.stringify({
        city: result,
        longitude: data.longitude,
        latitude: data.latitude
      }));
      this.$toast('定位成功')
      this.map.panTo(new qq.maps.LatLng(data.latitude, data.longitude));
      this.map.setZoom(11)
    },
    // 获取当前楼盘信息
    getCurrentLinker(linkerId) {
      let currentLinker = this.linkerList.filter(item => item.linkerId == linkerId).map(item => {
        const tags = ['在售', '待售', '售罄'];
        return {
          ...item,
          linkerUrl: item.linkerImg,
          price: item.linkerPrice,
          district: item.linkerAddress,
          city: '',
          buildArea: item.minArea ? `${item.minArea}-${item.maxArea}` : '',
          linkerTags: [tags[item.saleStatus], ...item.linkerTags]
        }
      });
      this.currentLinker = currentLinker[0];
    }
  }
}
</script>


<style lang="less">
#map-container-market {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  font-size: 12px;
  color: #fff;
  .area-text {
    margin: auto;
    // padding: 0 15px;
    height: 74px;
    width: 74px;
    // line-height: 52px;
    text-align: center;
    background-color: rgba(0, 122, 230, 0.9);
    box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.3);
    border-radius: 50%;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  .linker-text {
    width: 128px;
    height: 48px;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: rgba(0, 122, 230, 0.9);
    // box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 0.3);
    border-radius: 22px;
  }
  .arrow {
    position: absolute;
    left: 50%;
    width: 0;
    height: 0;
    top: 48px;
    border-width: 5px;
    border-style: solid;
    border-color: rgba(0, 122, 230, 0.9) transparent transparent transparent;
    transform: translateX(-50%);
  }
  .name {
    display: block;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    width: 90%;
  }
  .nav-bar {
    width: 100%;
    height: 38px;
    line-height: 38px;
    position: fixed;
    top: 0;
    left: 0;
    background: rgba(255, 255, 255, 1);
    box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.3);
    z-index: 999;
    text-align: center;
    font-size: 12px;
    font-weight: 400;
    color: rgba(102, 102, 102, 1);
  }
  .location-icon {
    height: 40px;
    width: 40px;
    position: fixed;
    left: 13px;
    bottom: 25px;
    z-index: 999;
  }
  .location-suspension {
    bottom: 155px;
  }
  .linker-shade {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background: #fff;
    z-index: 99;
  }
}
</style>
